from pylab import *
from core.Setting import db_win
from wxy_MySQL import MySQLdb

mpl.rcParams['font.sans-serif'] = ['SimHei']


def Adaptive(num):
    '''传入数据个数，更具数据个数确定倍数'''
    if num <= 250:
        return 10
    else:
        return int(num*10 / 250)

class ServerData:

    marker_size=0

    def __init__(self,db,data_table,I_name,I_id):
        '''
        从测试数据表中取得监控范围，在到监控数据表中提取监控信息
        自适应：
              x=250   ---->  10:5
              x=500   ---->  20:5
              x=750   ---->  30:5
              x=1000  ---->  40:5
        :param db:数据库实例
        :param data_table:测试数据存储表
        :param monitor_table:监控数据存储表
        :param I_name:接口名称
        :param I_id:数据id
        :param save_path:接口目录
        :return:
        '''
        self.s_time = db.select(data_table, 's_time', 'I_id="{}" and I_name="{}"'.format(I_id, I_name), sql=False)[0]
        self.e_time = db.select(data_table, 'e_time', 'I_id="{}" and I_name="{}"'.format(I_id, I_name), sql=False)[0]
        self.I_name=I_name
        self.I_id=I_id
        self.db = db

    def Web(self,monitor_table,cpu_path,memory_path,TCP_path):
        # 查询条件
        condition='timestamp>"{}" and timestamp<"{}"'.format(self.s_time, self.e_time)
        cpu = [float(i) for i in self.db.select(monitor_table,'cpu',condition)]  # cpu 数据列表
        memory = [float(i) for i in self.db.select(monitor_table,'memory',condition)]   # memory 数据列表
        tcp_e = [int(i) for i in self.db.select(monitor_table,'TCP_e',condition)]   # tcp_e 数据列表
        tcp_c = [int(i) for i in self.db.select(monitor_table,'TCP_c',condition)]   # tcp_e 数据列表
        x = list(range(len(cpu)))
        avg_cpu = round((sum(cpu) / len(cpu)), 1)
        avg_memory = round((sum(memory) / len(memory)), 1)
        avg_tcp = int((sum(tcp_e)+sum(tcp_c))/len(tcp_c))

        def cpu_image():

            plt.figure(figsize=(Adaptive(len(x)), 5))
            plt.ylim([0, 105])
            plt.plot(x, cpu, marker='o', markersize=ServerData.marker_size, markerfacecolor='brown', c='brown')
            plt.xlabel('time')
            plt.ylabel('CPU占用率(%)')
            plt.title('web服务器CPU利用率')
            plt.legend(['cpu'], loc=2)
            plt.savefig(cpu_path + '\\CPU_({})_{}.png'.format(self.I_name, self.I_id))

        def memory_image():

            plt.figure(figsize=(Adaptive(len(x)), 5))
            plt.ylim([0, 105])
            plt.plot(x, memory, marker='o', markersize=ServerData.marker_size, markerfacecolor='brown', c='brown')
            plt.xlabel('time')
            plt.ylabel('memory占用率(%)')
            plt.title('web服务器memory占用')
            plt.legend(['memory'], loc=2)
            plt.savefig(memory_path + '\\Memory_({})_{}.png'.format(self.I_name, self.I_id))

        def tcp_image():

            plt.figure(figsize=(Adaptive(len(x)), 5))
            max_c=max(tcp_c)
            max_e=max(tcp_e)
            max_tcp=max([max_c,max_e])
            plt.ylim([0, max_tcp+300])
            plt.plot(x, tcp_e, marker='o', markersize=ServerData.marker_size, markerfacecolor='green', c='green')
            plt.plot(x, tcp_c, marker='o', markersize=ServerData.marker_size, markerfacecolor='red', c='red')
            plt.xlabel('time')
            plt.ylabel('TCP连接数')
            plt.title('web服务器TCP连接数')
            plt.legend(['Establshed','Close_Wait'], loc=2)
            plt.savefig(TCP_path + '\\TCP_({})_{}.png'.format(self.I_name, self.I_id))


        cpu_image()
        memory_image()
        tcp_image()

        plt.cla()
        plt.close("all")

        return [avg_cpu,avg_memory,avg_tcp]

    def Redis(self,monitor_table,cpu_path,memory_path,TCP_path):

        # 查询条件
        condition='timestamp>"{}" and timestamp<"{}"'.format(self.s_time, self.e_time)
        cpu = [float(i) for i in self.db.select(monitor_table,'cpu',condition)]  # cpu 数据列表
        memory = [float(i) for i in self.db.select(monitor_table,'memory',condition)]   # memory 数据列表
        tcp_e = [int(i) for i in self.db.select(monitor_table,'TCP_e',condition)]   # tcp_e 数据列表
        tcp_c = [int(i) for i in self.db.select(monitor_table,'TCP_c',condition)]   # tcp_e 数据列表
        x = list(range(len(cpu)))
        avg_cpu = round((sum(cpu) / len(cpu)), 1)
        avg_memory = round((sum(memory) / len(memory)), 1)
        avg_tcp = int((sum(tcp_e) + sum(tcp_c)) / len(tcp_c))

        def cpu_image():

            plt.figure(figsize=(Adaptive(len(x)), 5))
            plt.ylim([0, 105])
            plt.plot(x, cpu, marker='o', markersize=ServerData.marker_size, markerfacecolor='brown', c='brown')
            plt.xlabel('time')
            plt.ylabel('CPU占用率(%)')
            plt.title('redis服务器CPU利用率')
            plt.legend(['cpu'], loc=2)
            plt.savefig(cpu_path + '\\CPU_({})_{}.png'.format(self.I_name, self.I_id))

        def memory_image():

            plt.figure(figsize=(Adaptive(len(x)), 5))
            plt.ylim([0, 105])
            plt.plot(x, memory, marker='o', markersize=ServerData.marker_size, markerfacecolor='brown', c='brown')
            plt.xlabel('time')
            plt.ylabel('memory占用率(%)')
            plt.title('redis服务器memory占用')
            plt.legend(['memory'], loc=2)
            plt.savefig(memory_path + '\\Memory_({})_{}.png'.format(self.I_name, self.I_id))

        def tcp_image():

            plt.figure(figsize=(Adaptive(len(x)), 5))
            max_c=max(tcp_c)
            max_e=max(tcp_e)
            max_tcp=max([max_c,max_e])
            plt.ylim([0, max_tcp+300])
            plt.plot(x, tcp_e, marker='o', markersize=ServerData.marker_size, markerfacecolor='green', c='green')
            plt.plot(x, tcp_c, marker='o', markersize=ServerData.marker_size, markerfacecolor='red', c='red')
            plt.xlabel('time')
            plt.ylabel('TCP连接数')
            plt.title('web服务器TCP连接数')
            plt.legend(['Establshed','Close_Wait'], loc=2)
            plt.savefig(TCP_path + '\\TCP_({})_{}.png'.format(self.I_name, self.I_id))


        cpu_image()
        memory_image()
        tcp_image()

        plt.cla()
        plt.close("all")

        return [avg_cpu,avg_memory,avg_tcp]

    def Mongo(self,monitor_table,cpu_path,memory_path,TCP_path):

        # 查询条件
        condition='timestamp>"{}" and timestamp<"{}"'.format(self.s_time, self.e_time)
        cpu = [float(i) for i in self.db.select(monitor_table,'cpu',condition)]  # cpu 数据列表
        memory = [float(i) for i in self.db.select(monitor_table,'memory',condition)]   # memory 数据列表
        tcp_e = [int(i) for i in self.db.select(monitor_table,'TCP_e',condition)]   # tcp_e 数据列表
        tcp_c = [int(i) for i in self.db.select(monitor_table,'TCP_c',condition)]   # tcp_e 数据列表
        tcp_total = tcp_e + tcp_c
        x = list(range(len(cpu)))
        avg_cpu = round((sum(cpu) / len(cpu)), 1)
        avg_memory = round((sum(memory) / len(memory)), 1)
        avg_tcp = int((sum(tcp_e) + sum(tcp_c)) / len(tcp_c))

        def cpu_image():

            plt.figure(figsize=(Adaptive(len(x)), 5))
            plt.ylim([0, 105])
            plt.plot(x, cpu, marker='o', markersize=ServerData.marker_size, markerfacecolor='brown', c='brown')
            plt.xlabel('time')
            plt.ylabel('CPU占用率(%)')
            plt.title('mongo服务器CPU利用率')
            plt.legend(['cpu'], loc=2)
            plt.savefig(cpu_path + '\\CPU_({})_{}.png'.format(self.I_name, self.I_id))

        def memory_image():

            plt.figure(figsize=(Adaptive(len(x)), 5))
            plt.ylim([0, 105])
            plt.plot(x, memory, marker='o', markersize=ServerData.marker_size, markerfacecolor='brown', c='brown')
            plt.xlabel('time')
            plt.ylabel('memory占用率(%)')
            plt.title('mongo服务器memory占用')
            plt.legend(['memory'], loc=2)
            plt.savefig(memory_path + '\\Memory_({})_{}.png'.format(self.I_name, self.I_id))

        def tcp_image():

            plt.figure(figsize=(Adaptive(len(x)), 5))
            max_c=max(tcp_c)
            max_e=max(tcp_e)
            max_tcp=max([max_c,max_e])
            plt.ylim([0, max_tcp+300])
            plt.plot(x, tcp_e, marker='o', markersize=ServerData.marker_size, markerfacecolor='green', c='green')
            plt.plot(x, tcp_c, marker='o', markersize=ServerData.marker_size, markerfacecolor='red', c='red')
            plt.xlabel('time')
            plt.ylabel('TCP连接数')
            plt.title('web服务器TCP连接数')
            plt.legend(['Establshed','Close_Wait'], loc=2)
            plt.savefig(TCP_path + '\\TCP_({})_{}.png'.format(self.I_name, self.I_id))

        cpu_image()
        memory_image()
        tcp_image()

        plt.cla()
        plt.close("all")

        return [avg_cpu,avg_memory,avg_tcp]

if __name__ == '__main__':
    db=MySQLdb(db_win['host'],
               db_win['user'],
               db_win['password'],
               'performance_testing')
    condition = 'timestamp>"1556447453" and timestamp<"1556449488"'
    cpu=[float(i) for i in db.select('qqqqii','cpu',condition)][0:200] # cpu 数据列表
    x = list(range(len(cpu)))
    print(len(x))

    plt.figure(figsize=(Adaptive(len(x)), 5))
    plt.ylim([0,200])
    plt.plot(x, cpu, marker='o', markersize=1, markerfacecolor='brown', c='brown')
    plt.xlabel('time')
    plt.ylabel('CPU占用率(%)')
    plt.title('web服务器CPU利用率')
    plt.legend(['cpu'], loc=2)



    plt.savefig('D:\Python\Auto_Testing\\xxxxx.png')
